import MapCommon from "../common/MapCommon";

/**
 * 缓存绘制图层
 */
export default class TempLayer {
  constructor(map) {
    this.map=map;
    this.layerName="_tempLayer";
    this.features=[];
    this.init();
  }

  /**
   * 初始化
   */
  init(){
    //初始化已选择要素
    let selectSet={
      "type": "FeatureCollection",
      "features": this.features||[]
    };
    //将所有点击线图层转化为面图层
    //增加高亮图层
    if (!this.map.getSource(this.layerName)) {
      this.map.addSource(this.layerName, {
        "type": "geojson",
        "data": selectSet
      });
    }
    //添加选择集图层
    if (!this.map.getLayer(this.layerName)) {
      this.map.addLayer({
        id: this.layerName,
        source: this.layerName,
        "minzoom": 7,
        "maxzoom": 18,
        type: 'line',
        "paint": {
          "line-color": "#e21",
          "line-opacity": 1,
          "line-width": 6
        },
      });
    }
  }

  /**
   * 新增要素
   */
  addFeatures(features=[]){
    this.features=this.features.concat(features);
    if (this.map.getSource(this.layerName)) {
      let selectSet={
        "type": "FeatureCollection",
        "features": this.features||[]
      };
      this.map.getSource(this.layerName).setData(selectSet);
    }
  }

  /**
   * 清空要素
   */
  clearFeatures(){
    this.features=[];
    if (this.map.getSource(this.layerName)) {
      let selectSet={
        "type": "FeatureCollection",
        "features": this.features||[]
      };
      this.map.getSource(this.layerName).setData(selectSet);
    }
  }

  /**
   * 移除相关图层和数据源
   */
  remove(){
    this.features=[];
    if (this.map.getLayer(this.layerName)) {
      this.map.removeLayer(this.layerName);
    }
    if (this.map.getSource(this.layerName)) {
      this.map.removeSource(this.layerName);
    }
  }

}
